#!/usr/bin/python3
from tkinter import *

class Application(Frame):#继承Frame类

   def __init__(self, master):
      super(Application, self).__init__(master)
      self.grid()
      self.create_widgets()

   def create_widgets(self):
      menubar = Menu(self)#创建菜单
      filemenu = Menu(menubar)#菜单项的子菜单
      filemenu.add_command(label='Calculate', command=self.calculate)
      filemenu.add_command(label='Reset', command=self.clear)
      #子菜单的名称和点击命令
      menubar.add_cascade(label='File', menu=filemenu)
      #母菜单 menu=filemenu)
      menubar.add_command(label='Quit', command=root.quit)
      #另一个母菜单以及点击执行的命令操作command=root.quit)
      
      self.label1 = Label(self, text='The Bowling Calculator')
      self.label1.grid(row=0, columnspan=3)
     
      self.label2 = Label(self, text='Enter score for game 1:')
      self.label3 = Label(self, text='Enter score for game 2:')
      self.label4 = Label(self, text='Enter score for game 3:')
      self.label5 = Label(self, text='Average:')
      self.label2.grid(row=2, column=0)
      self.label3.grid(row=3, column=0)
      self.label4.grid(row=4, column=0)
      self.label5.grid(row=5, column=0)
      #Label创建的四个label的名称和位置布局
      self.score1 = Entry(self)
      self.score2 = Entry(self)
      self.score3 = Entry(self)
      self.average = Entry(self)
      #创建四个Entry输入文本框，下面为位置布局
      self.score1.grid(row=2, column=1)
      self.score2.grid(row=3, column=1)
      self.score3.grid(row=4, column=1)
      self.average.grid(row=5, column=1)
      
      self.button1 = Button(self, text='Calculate Average', command=self.calculate)
      self.button1.grid(row=6, column=0)
      self.button2 = Button(self, text='Clear result', command=self.clear)
      self.button2.grid(row=6, column=1)
      #创建两个按钮的名称和命令操作
      self.score1.focus_set()#定位光标到score1位置
      root.config(menu=menubar)#将菜单栏连接到根对象Tk

   def calculate(self):
      numScore1 = int(self.score1.get())#字符串转换为int
      numScore2 = int(self.score2.get())
      numScore3 = int(self.score3.get())
      total = numScore1 + numScore2 + numScore3
      average = total / 3#求出平均值
      strAverage = "{0:.2f}".format(average)#对average格式化保留两位小数
      self.average.insert(0, strAverage)#将格式化后的值插入average输入框中

   def clear(self):
      self.score1.delete(0, END)#将所有内容删掉
      self.score2.delete(0,END)
      self.score3.delete(0,END)
      self.average.delete(0,END)
      self.score1.focus_set()#光标再次定位到score1的位置

root = Tk()
root.title('Bowling Average Calculator')
root.geometry('500x200')
app = Application(root)
app.mainloop()
